import axios, { AxiosInstance, AxiosResponse, AxiosError } from 'axios'
import { showDialog } from 'vant';
import router from "../router"

// 定义响应数据的接口
interface ApiResponse<T = any> {
    code: number
    message: string
    data?: T
}

// 定义用户信息接口
interface UserInfo {
    password: string
    [key: string]: any
}

// 假设backendAPI是一个对象，包含baseUrl属性
const backendAPI = { baseUrl: 'http://120.26.226.99:8081' };

let instance: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let withToken: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let withTokenNoIntercept: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let commonResponse = function (res: AxiosResponse<ApiResponse>): Promise<AxiosResponse<ApiResponse>> {
    if (res.data.code === 100) {
        return Promise.resolve(res);
    }
    else {
        showDialog({ message: "请求错误，服务器返回错误信息：" + res.data.message });
        return Promise.reject(res.data.message);
    }
}

let commonErr = function (err: AxiosError): Promise<never> {
    console.log(err);
    showDialog({ message: "请求发生错误：" + err })
    return Promise.reject(err);
}

instance.interceptors.response.use(commonResponse, commonErr);

withToken.interceptors.request.use(
    config => {
        if (localStorage.user_info) {
            try {
                const userInfo: UserInfo = JSON.parse(localStorage.user_info);
                // 只使用token或ID作为授权信息，而不是整个password字段
                // 假设password字段实际上是一个token
                if (userInfo.password && typeof userInfo.password === 'string') {
                    // 如果password非常长（可能包含了其他数据），只取前面一部分
                    const authToken = userInfo.password.length > 1000 ? 
                        userInfo.password.substring(0, 1000) : userInfo.password;
                    config.headers["Authorization"] = authToken;
                }
            } catch (error) {
                console.error('解析用户信息失败:', error);
                // 清除可能损坏的用户信息
                localStorage.removeItem('user_info');
            }
        }
        return config;
    },
    err => {
        showDialog({ message: '请求超时' })
        return Promise.reject(err)
    }
);

withToken.interceptors.response.use(
    res => {
        if (res.data.code === 100) {
            return res.data;
        }
        else if (res.data.code === 102) {
            showDialog({
                message: "尚未登陆，需要登陆",
                confirmButtonText: "前往登录",
            })
                .then(function () {
                    router.push("/Mlogin");
                })
                .catch(function () {
                    //留在当前页。
                })
            return Promise.reject(res.data.message);
        }
        else if (res.data.code === 103) {
            showDialog({
                message: "密码错误，请重新输入",
                confirmButtonText: "确认",
            })
        }
        else {
            showDialog({ message: "请求错误，服务器返回：" + res.data.message })
            return Promise.reject(res.data.message);
        }

    }, err => {
        console.log(err);
        showDialog({ message: "发生错误！" + err })
        return Promise.reject(err);
    }
);

withTokenNoIntercept.interceptors.request.use(
    config => {
        if (localStorage.user_info) {
            const userInfo: UserInfo = JSON.parse(localStorage.user_info);
            config.headers["Authorization"] = userInfo.password;
        }
        return config;
    },
    err => {
        showDialog({ message: '请求超时' })
        return Promise.reject(err)
    }
);


withTokenNoIntercept.interceptors.response.use(
    res => {
        if (res.data.code === 100) {
            return res.data;
        }
        else if (res.data.code === 102) {
            return Promise.reject("权限不够");
        }
        else {
            showDialog({ message: "请求错误，服务器返回：" + res.data.message })
            return Promise.reject(res.data.message);
        }

    }, err => {
        showDialog({ message: "发生错误！" + err })
        return Promise.reject(err);
    }
);

// 导出 API 实例
const api = {
    login(users: any) {
        return instance.post("/users/login", users);
    },
    register(users: any) {
        return instance.post("/users/register", users);
    },
    forgotPassword(users: any) {
        return instance.post("/users/forgotPassword", users);
    },
    getInfo() {
        return withToken.get("/users/getInfo");
    },
    checkLogin() {
        return withToken.get("/users/checklog");
    },
    getTaskList() {
        return instance.get("/tasks/getTaskList");
    },
    increaseViewCount(taskId: any){
        return withToken.get("/tasks/increaseViewCount?taskId=" + taskId);
    },
    applyTask(taskId: any){
        return withToken.post("/tasks/applyTask?taskId=" + taskId);
    },
    getTaskDetail(taskId: any){
        return instance.get("/tasks/getTaskDetail?taskId=" + taskId);
    },
    updateTaskExpiration(){
        return instance.get("/tasks/updateTaskExpiration");
    },
    getSimilarTasks(taskId: any){
        return instance.get("/tasks/getSimilarTasks?taskId=" + taskId);
    },
    searchTasks(keyword: any){
        return instance.get("/tasks/searchTasks?keyword=" + keyword);
    },
    updateInfo(user: any){
        return withToken.post("/users/updateInfo", user);
    },
    publishTask(task: any){
        return withToken.post("/tasks/publishTask", task);
    },
    getMyPublishedTasks(){
        return withToken.get("/tasks/getMyPublishedTasks");
    },
    getMyAppliedTasks(){
        return withToken.get("/tasks/getMyAppliedTasks");
    },
    cancelApply(taskId: any){
        return withToken.post("/tasks/cancelApply?taskId=" + taskId);
    },
    cancelTask(taskId: any){
        return withToken.post("/tasks/cancelTask?taskId=" + taskId);
    },
    generateOrder(taskId: any){
        return withToken.get("/tasks/generateOrder?taskId=" + taskId);
    },
    getOrderList(){
        return withToken.get("/taskOrders/getOrders");
    },
    searchOrders(keyword: any){
        return withToken.get("/taskOrders/searchOrders?keyword=" + keyword);
    },
    getMyPublishedOrders(){
        return withToken.get("/taskOrders/getMyPublishedOrders");
    },
    getMyAcceptedOrders(){
        return withToken.get("/taskOrders/getMyAcceptedOrders");
    },
    getOrderDetail(orderId: any){
        return withToken.get("/taskOrders/getOrderDetail?orderId=" + orderId);
    },
    isPublisher(taskId: any){
        return withTokenNoIntercept.get("/tasks/isPublisher?taskId=" + taskId);
    },
    isAlreadyApplied(taskId: any){
        return withTokenNoIntercept.get("/tasks/isAlreadyApplied?taskId=" + taskId);
    },
    hasLogin(){
        return withTokenNoIntercept.get("/users/checklog");
    },
    getUserInfo(userId: any){
        return withToken.get("/users/getUserInfo?userId=" + userId);
    },
    cancelOrder(orderId: any){
        return withToken.post("/taskOrders/cancelOrder?orderId=" + orderId);
    },
    completeOrder(orderId: any){
        return withToken.post("/taskOrders/completeOrder?orderId=" + orderId);
    },
    getWalletInfo(){
        return withToken.get("/wallets/getWalletInfo");
    },
    submitPayment(payment: any){
        return withToken.post("/payments/submitPayment", payment);
    },
    getTransactions(){
        return withToken.get("/walletTransactions/getTransactions");
    },
    getPublisherInfo(userId: any){
        return withToken.get("/users/getPublisherInfo?userId=" + userId);
    },
    submitRating(rating: any){
        return withToken.post("/ratings/submitRating", rating);
    },
    getAvatar() {
        return withToken.get("/users/getAvatar");
    },
    getUserRatingStats(userId: any){
        return withToken.get("/ratings/getUserRatingStats?userId=" + userId);
    },
    getTaskByCategory(categoryId: any){
        return instance.get("/tasks/getTaskByCategory?categoryId=" + categoryId);
    },
    getRatingsTo(){
        return withToken.get("/ratings/getRatingsTo");
    },
    getRatingsFrom(){
        return withToken.get("/ratings/getRatingsFrom");
    },
    uploadAvatar(formData: any) {
        return withToken.post("/users/uploadAvatar", formData);
    },
    getAvatarById(id: any){
        return instance.get("/users/getAvatarById?id=" + id);
    }
}

export default api
